<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Javascript,">










<meta name="description" content="方式一： 原生的 js 循环1.while 循环:While语句包括一个循环条件和一段代码块，只要条件为真，就不断循环执行代码块。 12345678while (条件) 语句;  //举例：var i = 0; while (i &amp;lt; 10) &amp;#123;     console.log(&apos;i 当前为：&apos; + i); i = i + 1; &amp;#125; 2. do……while循环do…whi">
<meta name="keywords" content="Javascript">
<meta property="og:type" content="article">
<meta property="og:title" content="javascript的循环遍历">
<meta property="og:url" content="elfeach.gitee.io/2020/10/29/javascript的循环遍历/index.html">
<meta property="og:site_name" content="Elfecho’Blog">
<meta property="og:description" content="方式一： 原生的 js 循环1.while 循环:While语句包括一个循环条件和一段代码块，只要条件为真，就不断循环执行代码块。 12345678while (条件) 语句;  //举例：var i = 0; while (i &amp;lt; 10) &amp;#123;     console.log(&apos;i 当前为：&apos; + i); i = i + 1; &amp;#125; 2. do……while循环do…whi">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-11-01T13:51:12.970Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="javascript的循环遍历">
<meta name="twitter:description" content="方式一： 原生的 js 循环1.while 循环:While语句包括一个循环条件和一段代码块，只要条件为真，就不断循环执行代码块。 12345678while (条件) 语句;  //举例：var i = 0; while (i &amp;lt; 10) &amp;#123;     console.log(&apos;i 当前为：&apos; + i); i = i + 1; &amp;#125; 2. do……while循环do…whi">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"没有找到与[${query}]相关的内容","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="elfeach.gitee.io/2020/10/29/javascript的循环遍历/">





  <title>javascript的循环遍历 | Elfecho’Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c491056d7021e5c248129f6222a89004";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  <script type="text/javascript" src="/js/src/crash_cheat.js"></script>
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Elfecho’Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">有空时来歇歇脚吧</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="elfeach.gitee.io/2020/10/29/javascript的循环遍历/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="elfecho">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Elfecho’Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">javascript的循环遍历</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-29T09:20:25+08:00">
                2020-10-29
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            
            
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.1k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  13 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="方式一：-原生的-js-循环"><a href="#方式一：-原生的-js-循环" class="headerlink" title="方式一： 原生的 js 循环"></a>方式一： 原生的 js 循环</h2><h3 id="1-while-循环"><a href="#1-while-循环" class="headerlink" title="1.while 循环:"></a>1.while 循环:</h3><p>While语句包括一个循环条件和一段代码块，只要条件为真，就不断循环执行代码块。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> (条件) 语句; </span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"><span class="comment">//举例：</span></span><br><span class="line"><span class="keyword">var</span> i = <span class="number">0</span>; </span><br><span class="line"><span class="keyword">while</span> (i &lt; <span class="number">10</span>) &#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'i 当前为：'</span> + i); i = i + <span class="number">1</span>; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-do……while循环"><a href="#2-do……while循环" class="headerlink" title="2. do……while循环"></a>2. do……while循环</h3><p>do…while循环与while循环类似，唯一的区别就是先执行再判断，即使初始条件不成立，do-while循环至少执行一次，也就是说do-while循环比while循环多执行一次</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">do &#123; </span><br><span class="line">    语句 </span><br><span class="line">&#125; while (条件);</span><br><span class="line"> </span><br><span class="line">//举例：</span><br><span class="line">var x = 3;</span><br><span class="line">var i = 0; </span><br><span class="line"> </span><br><span class="line">do &#123; </span><br><span class="line">    console.log(i); i++; </span><br><span class="line">&#125; while(i &lt; x);</span><br></pre></td></tr></table></figure>
<h3 id="3-for循环："><a href="#3-for循环：" class="headerlink" title="3.for循环："></a>3.for循环：</h3><ol>
<li><p>for循环的执行特点：先判断再执行，与while相同　　</p>
</li>
<li><p>for循环三个表达式都可以有多部分组成，第二部分多个判断条件用&amp;&amp; ||连接，第一三部分用逗号分割；</p>
</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> filterarray = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>]</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>; i&lt;filterarray.length; i++)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(filterarray[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-增强for…in循环："><a href="#4-增强for…in循环：" class="headerlink" title="4.增强for…in循环："></a>4.增强for…in循环：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">a</span>: <span class="number">1</span>, <span class="attr">b</span>: <span class="number">2</span>, <span class="attr">c</span>: <span class="number">3</span>&#125;; </span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> obj) &#123; </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'键名：'</span>, i); </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'键值：'</span>, obj[i]); </span><br><span class="line">&#125; </span><br><span class="line"><span class="comment">// 键名： a // 键值： 1 // 键名： b // 键值： 2</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">// 其中 obj为循环的对象， i 为对象中的“键名”。如果对象是数组，那么i就是坐标。</span></span><br></pre></td></tr></table></figure>
<p>注意：fo…in循环一般用于对象的遍历，但是这里有一个坑需要注意：</p>
<p>​    任何对象都继承了Object对象，或者其它对象，继承的类的属性是默认不可遍历的，for<code>...</code> in循环遍历的时候会跳过，但是这个属性是可以更改为可以遍历的，那么就会造成遍历到不属于自身的属性。</p>
<p>举例来说，对象都继承了<code>toString</code>属性，但是<code>for...in</code>循环不会遍历到这个属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;&#125;;<span class="comment">// toString 属性是存在的obj.toString </span></span><br><span class="line"><span class="comment">// toString() &#123; [native code] &#125;</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> p <span class="keyword">in</span> obj) &#123; </span><br><span class="line">     <span class="built_in">console</span>.log(p);</span><br><span class="line">&#125; <span class="comment">// 没有任何输出</span></span><br></pre></td></tr></table></figure>
<p>如果继承的属性是可遍历的，那么就会被<code>for...in</code>循环遍历到。但如果只想遍历自身的属性，使用<code>for...in</code>的时候，应该结合使用<code>hasOwnProperty</code>方法，在循环内部判断一下，某个属性是否为对象自身的属性。否则就可以产生遍历失真的情况。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> person = &#123; <span class="attr">name</span>: <span class="string">'老张'</span> &#125;;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> person) &#123;  </span><br><span class="line">    <span class="keyword">if</span> (person.hasOwnProperty(key)) &#123;   </span><br><span class="line">         <span class="built_in">console</span>.log(key);</span><br><span class="line">      &#125;</span><br><span class="line">&#125;<span class="comment">// name</span></span><br></pre></td></tr></table></figure>
<p>此外，for循环遍历json对象有点奇葩：</p>
<p>无规律json数组：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> json = [&#123;<span class="attr">dd</span>:<span class="string">'SB'</span>,<span class="attr">AA</span>:<span class="string">'东东'</span>,<span class="attr">re1</span>:<span class="number">123</span>&#125;, &#123;<span class="attr">cccc</span>:<span class="string">'dd'</span>,<span class="attr">lk</span>:<span class="string">'1qw'</span>&#125;];</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>,l=json.length;i&lt;l;i++)&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> json[i])&#123;</span><br><span class="line">        alert(key+<span class="string">':'</span>+json[i][key]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为嵌套了多层，所以需要使用嵌套多一层for</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> packJson = [</span><br><span class="line">    &#123;<span class="string">"name"</span>: <span class="string">"nikita"</span>, <span class="string">"password"</span>: <span class="string">"1111"</span>&#125;,</span><br><span class="line">    &#123;<span class="string">"name"</span>: <span class="string">"tony"</span>, <span class="string">"password"</span>: <span class="string">"2222"</span>&#125;</span><br><span class="line">];</span><br><span class="line"> </span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> p <span class="keyword">in</span> packJson) &#123;<span class="comment">//遍历json数组时，这么写p为索引，0,1</span></span><br><span class="line">    alert(packJson[p].name + <span class="string">" "</span> + packJson[p].password);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="5-map-循环："><a href="#5-map-循环：" class="headerlink" title="5.map()循环："></a>5.map()循环：</h2><p>map方法将数组的所有成员依次传入参数函数，然后把每一次的执行结果组成一个新数组返回。</p>
<p>注意：是返回一个新数组，而不会改变原数组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> numbers = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"> </span><br><span class="line">numbers.map(<span class="function"><span class="keyword">function</span> (<span class="params">n</span>) </span>&#123; </span><br><span class="line">     <span class="keyword">return</span> n + <span class="number">1</span>; </span><br><span class="line">&#125;); </span><br><span class="line"><span class="comment">// [2, 3, 4] </span></span><br><span class="line"> </span><br><span class="line">numbers <span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>
<p>map方法接受一个函数作为参数。该函数调用时，map方法向它传入三个参数：当前成员、当前位置和数组本身。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>].map(<span class="function"><span class="keyword">function</span>(<span class="params">elem, index, arr</span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> elem * index; </span><br><span class="line">&#125;); </span><br><span class="line"><span class="comment">// [0, 2, 6]</span></span><br></pre></td></tr></table></figure>
<p>此外，map()循环还可以接受第二个参数，用来绑定回调函数内部的this变量，将回调函数内部的this对象，指向第二个参数，间接操作这个参数（一般是数组）。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>];</span><br><span class="line"> </span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>].map(<span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'this'</span>, <span class="keyword">this</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>[e];</span><br><span class="line">&#125;, arr)</span><br><span class="line"> <span class="comment">// ['b', 'c']</span></span><br></pre></td></tr></table></figure>
<p>上面代码通过map方法的第二个参数，将回调函数内部的this对象，指向arr数组。间接操作了数组arr; forEach同样具有这个功能。</p>
<h3 id="6-forEach循环"><a href="#6-forEach循环" class="headerlink" title="6.forEach循环"></a>6.forEach循环</h3><p>​    forEach方法与map方法很相似，也是对数组的所有成员依次执行参数函数。但是，forEach方法不返回值，只用来操作数据。也就是说，如果数组遍历的目的是为了得到返回值，那么使用map方法，否则使用forEach方法。forEach的用法与map方法一致，参数是一个函数，该函数同样接受三个参数：当前值、当前位置、整个数组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">log</span>(<span class="params">element, index, array</span>) </span>&#123;</span><br><span class="line">     <span class="built_in">console</span>.log(<span class="string">'['</span> + index + <span class="string">'] = '</span> + element); </span><br><span class="line">&#125; ；</span><br><span class="line"> </span><br><span class="line">[<span class="number">2</span>, <span class="number">5</span>, <span class="number">9</span>].forEach(log); <span class="comment">// [0] = 2 // [1] = 5 // [2] = 9</span></span><br></pre></td></tr></table></figure>
<p>此外，forEach循环和map循环一样也可以用绑定回调函数内部的this变量，间接操作其它变量（参考上面的map()循环例子）</p>
<h3 id="7-filter-过滤循环"><a href="#7-filter-过滤循环" class="headerlink" title="7.filter()过滤循环"></a>7.filter()过滤循环</h3><p>​    filter方法用于过滤数组成员，满足条件的成员组成一个新数组返回。它的参数是一个函数，所有数组成员依次执行该函数，返回结果为true的成员组成一个新数组返回。该方法不会改变原数组</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>].filter(<span class="function"><span class="keyword">function</span> (<span class="params">elem</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">return</span> (elem &gt; <span class="number">3</span>); </span><br><span class="line">&#125;) <span class="comment">// [4, 5]</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">// 上面代码将大于3的数组成员，作为一个新数组返回。</span></span><br><span class="line"> </span><br><span class="line"><span class="keyword">var</span> arr = [<span class="number">0</span>, <span class="number">1</span>, <span class="string">'a'</span>, <span class="literal">false</span>]; </span><br><span class="line">arr.filter(<span class="built_in">Boolean</span>) <span class="comment">// [1, "a"]</span></span><br></pre></td></tr></table></figure>
<p>filter方法的参数函数也可以接受三个参数：当前成员，当前位置和整个数 组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>].filter(<span class="function"><span class="keyword">function</span> (<span class="params">elem, index, arr</span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> index % <span class="number">2</span> === <span class="number">0</span>; </span><br><span class="line">&#125;); <span class="comment">// [1, 3, 5]</span></span><br></pre></td></tr></table></figure>
<p>此外，filter方法也可以接受第二个参数，用来绑定参数函数内部的this变量。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123; <span class="attr">MAX</span>: <span class="number">3</span> &#125;; <span class="keyword">var</span> myFilter = <span class="function"><span class="keyword">function</span> (<span class="params">item</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">if</span> (item &gt; <span class="keyword">this</span>.MAX) <span class="keyword">return</span> <span class="literal">true</span>; </span><br><span class="line">&#125;; </span><br><span class="line"><span class="keyword">var</span> arr = [<span class="number">2</span>, <span class="number">8</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">1</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">9</span>]; </span><br><span class="line">arr.filter(myFilter, obj) <span class="comment">// [8, 4, 9]</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，过滤器<code>myFilter</code>内部有<code>this</code>变量，它可以被<code>filter</code>方法的第二个参数<code>obj</code>绑定，返回大于<code>3</code>的成员。</p>
<h3 id="8-some-，every-循环遍历，统计数组是否满足某个条件"><a href="#8-some-，every-循环遍历，统计数组是否满足某个条件" class="headerlink" title="8.some()，every()循环遍历，统计数组是否满足某个条件"></a><strong>8.</strong>some()，every()循环遍历，统计数组是否满足某个条件</h3><p>​     这两个方法类似“断言”（assert），返回一个布尔值，表示判断数组成员是否符合某种条件。</p>
<p>​    它们接受一个函数作为参数，所有数组成员依次执行该函数。该函数接受三个参数：当前成员、当前位置和整个数组，然后返回一个布尔值。</p>
<p><code>some</code>方法是只要一个成员的返回值是<code>true</code>，则整个<code>some</code>方法的返回值就是<code>true</code>，否则返回<code>false</code>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line">arr.some(<span class="function"><span class="keyword">function</span> (<span class="params">elem, index, arr</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> elem &gt;= <span class="number">3</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<p><code>而every</code>方法则相反，所有成员的返回值都是<code>true</code>，整个<code>every</code>方法才返回<code>true</code>，否则返回<code>false</code>。两相比较，some()只要有一个是true，便返回true；而every()只要有一个是false，便返回false.</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line">arr.every(<span class="function"><span class="keyword">function</span> (<span class="params">elem, index, arr</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> elem &gt;= <span class="number">3</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<p>​    这两个方法在实际开发中，大有可用之处。比如在判定用户是否勾选了不可操作的数据，或者是否勾选了一条可以操作的数据可以使用这两个方法遍历循环数组。</p>
<h3 id="9-reduce-，reduceRight-方法可依次处理数组的每个成员"><a href="#9-reduce-，reduceRight-方法可依次处理数组的每个成员" class="headerlink" title="9.reduce()，reduceRight()方法可依次处理数组的每个成员"></a><strong>9.reduce()，reduceRight()</strong>方法可依次处理数组的每个成员</h3><p>​     <code>reduce</code>方法和<code>reduceRight</code>方法依次处理数组的每个成员，最终累计为一个值。它们的差别是，<code>reduce</code>是从左到右处理（从第一个成员到最后一个成员），<code>reduceRight</code>则是从右到左（从最后一个成员到第一个成员），其他完全一样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>].reduce(<span class="function"><span class="keyword">function</span> (<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(a, b);</span><br><span class="line">  <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 1 2</span></span><br><span class="line"><span class="comment">// 3 3</span></span><br><span class="line"><span class="comment">// 6 4</span></span><br><span class="line"><span class="comment">// 10 5</span></span><br><span class="line"><span class="comment">//最后结果：15</span></span><br></pre></td></tr></table></figure>
<p><code>reduce</code>方法和<code>reduceRight</code>方法的第一个参数都是一个函数。该函数接受以下四个参数。</p>
<ol>
<li>累积变量，默认为数组的第一个成员</li>
<li>当前变量，默认为数组的第二个成员</li>
<li>当前位置（从0开始）</li>
<li>原数组</li>
</ol>
<p>这四个参数之中，只有前两个是必须的，后两个则是可选的。</p>
<p>   如果要对累积变量指定初值，可以把它放在<code>reduce</code>方法和<code>reduceRight</code>方法的第二个参数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>].reduce(<span class="function"><span class="keyword">function</span> (<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;, <span class="number">10</span>);</span><br><span class="line"><span class="comment">// 25</span></span><br></pre></td></tr></table></figure>
<p>​    上面的第二个参数相当于设定了默认值，处理空数组时尤其有用，可避免一些空指针异常。</p>
<p>​    由于这两个方法会遍历数组，所以实际上还可以用来做一些遍历相关的操作。比如，找出字符长度最长的数组成员。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">findLongest</span>(<span class="params">entries</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> entries.reduce(<span class="function"><span class="keyword">function</span> (<span class="params">longest, entry</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> entry.length &gt; longest.length ? entry : longest;</span><br><span class="line">  &#125;, <span class="string">''</span>);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">findLongest([<span class="string">'aaa'</span>, <span class="string">'bb'</span>, <span class="string">'c'</span>]) <span class="comment">// "aaa"</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，<code>reduce</code>的参数函数会将字符长度较长的那个数组成员，作为累积值。这导致遍历所有成员之后，累积值就是字符长度最长的那个成员。</p>
<h3 id="10-Object-keys遍历对象的属性"><a href="#10-Object-keys遍历对象的属性" class="headerlink" title="10.Object.keys遍历对象的属性"></a><strong>10.Object.keys</strong>遍历对象的属性</h3><p><code>Object.keys</code>方法的参数是一个对象，返回一个数组。该数组的成员都是该对象自身的（而不是继承的）所有属性名，且只返回可枚举的属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  p1: <span class="number">123</span>,</span><br><span class="line">  p2: <span class="number">456</span></span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="built_in">Object</span>.keys(obj) <span class="comment">// ["p1", "p2"]</span></span><br></pre></td></tr></table></figure>
<h3 id="11-Object-getOwnPropertyNames-遍历对象的属性"><a href="#11-Object-getOwnPropertyNames-遍历对象的属性" class="headerlink" title="11.Object.getOwnPropertyNames()遍历对象的属性"></a><strong>11.<code>Object.getOwnPropertyNames()</code>遍历对象的属性</strong></h3><p><code>Object.getOwnPropertyNames</code>方法与<code>Object.keys</code>类似，也是接受一个对象作为参数，返回一个数组，包含了该对象自身的所有属性名。但它能返回不可枚举的属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = [<span class="string">'Hello'</span>, <span class="string">'World'</span>];</span><br><span class="line"> </span><br><span class="line"><span class="built_in">Object</span>.keys(a) <span class="comment">// ["0", "1"]</span></span><br><span class="line"><span class="built_in">Object</span>.getOwnPropertyNames(a) <span class="comment">// ["0", "1", "length"]</span></span><br></pre></td></tr></table></figure>
<p>上面代码中，数组的<code>length</code>属性是不可枚举的属性，所以只出现在<code>Object.getOwnPropertyNames</code>方法的返回结果中。</p>
<p>由于 JavaScript 没有提供计算对象属性个数的方法，所以可以用这两个方法代替。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  p1: <span class="number">123</span>,</span><br><span class="line">  p2: <span class="number">456</span></span><br><span class="line">&#125;;</span><br><span class="line"> </span><br><span class="line"><span class="built_in">Object</span>.keys(obj).length <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">Object</span>.getOwnPropertyNames(obj).length <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<h3 id="以上循环特征（相同与不同）："><a href="#以上循环特征（相同与不同）：" class="headerlink" title="以上循环特征（相同与不同）："></a>以上循环特征（相同与不同）：</h3><p><strong>一：map()，foreach，filter循环的共同之处：</strong></p>
<p>   1.<strong>foreach</strong>，<strong>map</strong>，<strong>filter</strong>循环中途是无法停止的，总是会将所有成员遍历完。</p>
<p>   2.他们都可以接受第二个参数，用来绑定回调函数内部的this变量，将回调函数内部的this对象，指向第二个参数，间接操作这个参数（一般是数组）。</p>
<p><strong>二：map()循环和forEach循环的不同：</strong></p>
<p>​      forEach循环没有返回值；map，<strong>filter</strong>循环有返回值。</p>
<p><strong>三：map(环和filter()循环都会跳过空位，for和while不会</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> f = <span class="function"><span class="keyword">function</span> (<span class="params">n</span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> <span class="string">'a'</span> </span><br><span class="line">&#125;; </span><br><span class="line"> </span><br><span class="line">[<span class="number">1</span>, <span class="literal">undefined</span>, <span class="number">2</span>].map(f) <span class="comment">// ["a", "a", "a"] </span></span><br><span class="line">[<span class="number">1</span>, <span class="literal">null</span>, <span class="number">2</span>].map(f) <span class="comment">// ["a", "a", "a"]</span></span><br><span class="line">[<span class="number">1</span>, , <span class="number">2</span>].map(f) <span class="comment">// ["a", , "a"]</span></span><br></pre></td></tr></table></figure>
<p><strong>四：<code>some</code>()和<code>every():</code></strong></p>
<p>​    some()只要有一个是true，便返回true；而every()只要有一个是false，便返回false.</p>
<p><strong>五：reduce()，reduceRight()：</strong></p>
<p>​    <code>reduce</code>是从左到右处理（从第一个成员到最后一个成员），<code>reduceRight</code>则是从右到左（从最后一个成员到第一个成员）。</p>
<p><strong>六：Object对象的两个遍历<code>Object.keys与Object.getOwnPropertyNames</code>：</strong></p>
<p><code>他们都是遍历对象的属性</code>，也是接受一个对象作为参数，返回一个数组，包含了该对象自身的所有属性名。但<code>Object.keys</code>不能返回不可枚举的属性；<code>Object.getOwnPropertyNames</code>能返回不可枚举的属性。</p>
<h2 id="方式二：-使用JQuery-的遍历："><a href="#方式二：-使用JQuery-的遍历：" class="headerlink" title="方式二： 使用JQuery 的遍历："></a>方式二： 使用JQuery 的遍历：</h2><h3 id="1-grep-筛选遍历数组"><a href="#1-grep-筛选遍历数组" class="headerlink" title="1. $.grep()筛选遍历数组"></a>1. $.grep()筛选遍历数组</h3><p>​     <strong>grep()循环能够遍历数组，并筛选符合条件的元素，组成新的数组，并返回。</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> array = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>];</span><br><span class="line"><span class="keyword">var</span> filterarray = $.grep(array,<span class="function"><span class="keyword">function</span>(<span class="params">value</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> value &gt; <span class="number">5</span>;<span class="comment">//筛选出大于5的</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;filterarray.length;i++)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(filterarray[i]);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span> (key <span class="keyword">in</span> filterarray)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(filterarray[key]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-each-筛选遍历数组或json对象"><a href="#2-each-筛选遍历数组或json对象" class="headerlink" title="2.$.each()筛选遍历数组或json对象"></a>2.$.each()筛选遍历数组或json对象</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> anObject = &#123;<span class="attr">one</span>:<span class="number">1</span>,<span class="attr">two</span>:<span class="number">2</span>,<span class="attr">three</span>:<span class="number">3</span>&#125;;<span class="comment">//对json数组each</span></span><br><span class="line">$.each(anObject,<span class="function"><span class="keyword">function</span>(<span class="params">name,value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(name);</span><br><span class="line">    <span class="built_in">console</span>.log(value);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">var</span> anArray = [<span class="string">'one'</span>,<span class="string">'two'</span>,<span class="string">'three'</span>];</span><br><span class="line">$.each(anArray,<span class="function"><span class="keyword">function</span>(<span class="params">n,value</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(n);</span><br><span class="line">    <span class="built_in">console</span>.log(value);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="3-inArray-筛选遍历数组"><a href="#3-inArray-筛选遍历数组" class="headerlink" title="3.$.inArray()筛选遍历数组"></a>3.$.inArray()筛选遍历数组</h3><p>  inArray()循环能返回参数在数组中对应的坐标</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> anArray = [<span class="string">'one'</span>,<span class="string">'two'</span>,<span class="string">'three'</span>];</span><br><span class="line"><span class="keyword">var</span> index = $.inArray(<span class="string">'two'</span>,anArray);</span><br><span class="line"><span class="built_in">console</span>.log(index);<span class="comment">//返回该值在数组中的键值，返回1</span></span><br><span class="line"><span class="built_in">console</span>.log(anArray[index]);<span class="comment">//value is two</span></span><br></pre></td></tr></table></figure>
<h3 id="4-map-筛选遍历数组"><a href="#4-map-筛选遍历数组" class="headerlink" title="4.$.map()筛选遍历数组"></a>4.$.map()筛选遍历数组</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> strings = [<span class="string">'0'</span>,<span class="string">'1'</span>,<span class="string">'2'</span>,<span class="string">'3'</span>,<span class="string">'4'</span>,<span class="string">'S'</span>,<span class="string">'6'</span>]; </span><br><span class="line"><span class="keyword">var</span> values = $.map(strings,<span class="function"><span class="keyword">function</span>(<span class="params">value</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> result = <span class="keyword">new</span> <span class="built_in">Number</span>(value);</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">isNaN</span>(result) ? <span class="literal">null</span>:result;<span class="comment">//isNaN:is Not a Number的缩写</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">for</span> (key <span class="keyword">in</span> values) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(values[key]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>map循环常用语往数组中添加新元素，第二种写法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> list = [&#123;</span><br><span class="line">    name: <span class="string">'elfecho'</span></span><br><span class="line">&#125;]</span><br><span class="line">list.map(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">//往比遍历到的对象中添加属性</span></span><br><span class="line">    <span class="built_in">Object</span>.assign(item, &#123;</span><br><span class="line">        num: <span class="number">85</span></span><br><span class="line">    &#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>map() 把每个元素通过函数传递到当前匹配集合中，生成包含返回值的新的 jQuery 对象。此用法与原生js的map循环用法一致。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Javascript/" rel="tag"># Javascript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/10/28/浏览器的回流与重绘/" rel="next" title="浏览器的回流与重绘">
                <i class="fa fa-chevron-left"></i> 浏览器的回流与重绘
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/10/29/JS-Web-API-DOM/" rel="prev" title="JS-Web-API（BOM、DOM、事件、Ajax、存储）">
                JS-Web-API（BOM、DOM、事件、Ajax、存储） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="elfecho">
            
              <p class="site-author-name" itemprop="name">elfecho</p>
              <p class="site-description motion-element" itemprop="description">擅长各项前端技能，深入研究移动端开发与前端性能。非专业视觉设计师。此为博客一枚。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://elfeach.gitee.io/resume/" title="个人主页" target="_blank">个人主页</a>
                  </li>
                
              </ul>
            </div>
          
          <!-- 网易云音乐 
          <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=31421442&auto=1&height=66"></iframe> -->

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#方式一：-原生的-js-循环"><span class="nav-number">1.</span> <span class="nav-text">方式一： 原生的 js 循环</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-while-循环"><span class="nav-number">1.1.</span> <span class="nav-text">1.while 循环:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-do……while循环"><span class="nav-number">1.2.</span> <span class="nav-text">2. do……while循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-for循环："><span class="nav-number">1.3.</span> <span class="nav-text">3.for循环：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-增强for…in循环："><span class="nav-number">1.4.</span> <span class="nav-text">4.增强for…in循环：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-map-循环："><span class="nav-number">2.</span> <span class="nav-text">5.map()循环：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-forEach循环"><span class="nav-number">2.1.</span> <span class="nav-text">6.forEach循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-filter-过滤循环"><span class="nav-number">2.2.</span> <span class="nav-text">7.filter()过滤循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-some-，every-循环遍历，统计数组是否满足某个条件"><span class="nav-number">2.3.</span> <span class="nav-text">8.some()，every()循环遍历，统计数组是否满足某个条件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#9-reduce-，reduceRight-方法可依次处理数组的每个成员"><span class="nav-number">2.4.</span> <span class="nav-text">9.reduce()，reduceRight()方法可依次处理数组的每个成员</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#10-Object-keys遍历对象的属性"><span class="nav-number">2.5.</span> <span class="nav-text">10.Object.keys遍历对象的属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#11-Object-getOwnPropertyNames-遍历对象的属性"><span class="nav-number">2.6.</span> <span class="nav-text">11.Object.getOwnPropertyNames()遍历对象的属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#以上循环特征（相同与不同）："><span class="nav-number">2.7.</span> <span class="nav-text">以上循环特征（相同与不同）：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方式二：-使用JQuery-的遍历："><span class="nav-number">3.</span> <span class="nav-text">方式二： 使用JQuery 的遍历：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-grep-筛选遍历数组"><span class="nav-number">3.1.</span> <span class="nav-text">1. $.grep()筛选遍历数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-each-筛选遍历数组或json对象"><span class="nav-number">3.2.</span> <span class="nav-text">2.$.each()筛选遍历数组或json对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-inArray-筛选遍历数组"><span class="nav-number">3.3.</span> <span class="nav-text">3.$.inArray()筛选遍历数组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-map-筛选遍历数组"><span class="nav-number">3.4.</span> <span class="nav-text">4.$.map()筛选遍历数组</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">elfecho</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">39.6k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
